package com.example.blogback.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.blogback.common.Result;
import com.example.blogback.common.dto.LoginDto;
import com.example.blogback.entity.User;
import com.example.blogback.service.UserService;
import com.example.blogback.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
@Slf4j
public class AccountController {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;



    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        log.info("正式处理login请求");
//        从数据库进行查询
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user,"用户不存在");
//        System.out.println(user.getPassword());
//        System.out.println(SecureUtil.md5(loginDto.getPassword()));
//        使用MD5将密码散列
        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){

            return Result.fail("密码不正确");
        }
//        初次登录，返回token
        log.info("给用户返回token------->");
        String jwt = jwtUtils.generateToken(user.getId());
//        返回token
        response.setHeader("Authorization",jwt);
//        暴露header
        response.setHeader("Access-control-Expose-Headers","Authorization");
//        返回自定义结果
        log.info("login执行完毕，准备返回数据");
        return Result.success(MapUtil.builder()
                .put("id",user.getId())
                .put("username",user.getUsername())
                .put("avatar",user.getAvatar())
                .put("email",user.getEmail())
                .map()
        );

    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }


}
